package com.example.readFile;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class WriteFile {

    public static void main(String[] args) {
        String filePath = "D:\\tmp\\pwd.txt";
        String[] ss = {"22222222\r\n", "2131312312"};
        for (String s : ss) {
            writeSql(filePath, s, "UTF-8");
        }
    }


    public static void writeSql(String filePath, String sql, String charSet) {
        File file = new File(filePath);
        FileChannel fcout = null;
        FileLock flout = null;
        RandomAccessFile accessFile = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            // 对该文件加锁
            accessFile = new RandomAccessFile(file, "rw");
            fcout = accessFile.getChannel();
            while (true) {
                try {
                    flout = fcout.lock(); // 阻塞
                    break;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            accessFile.seek(accessFile.length());
            accessFile.write(sql.getBytes(charSet));
            flout.release();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fcout != null) {
                    fcout.close();
                }
                if (accessFile != null) {
                    accessFile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
